import {LockOutlined, UserOutlined} from "@ant-design/icons";
import {LoginForm, ProConfigProvider, ProFormText,} from "@ant-design/pro-components";
import {useDispatch} from "react-redux";
import {NavLink, useNavigate} from "react-router-dom";
import {getAdminUserInfo, login} from "../../api/userController.ts";
import {setLoginUser} from "../../store/loginUser.tsx";
import {message} from "antd";
import BaseResponseBoolean_ = API.BaseResponseBoolean;
import BaseResponseUserInfoVO_ = API.BaseResponseBoolean;

export default function Login() {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const handleLogin = async (values: API.LoginDto) => {
    let res: BaseResponseBoolean_ = await login(values);
    if (res.code === 200) {
      const result: BaseResponseUserInfoVO_ = await getAdminUserInfo();
      dispatch(setLoginUser(result.data));
      message.success("登录成功！");
      navigate("/home", { replace: true });
    } else {
      message.error(res.message);
    }
  };

  return (
    <div
      className={"login flex justify-center items-center"}
      style={{ height: "calc(100vh - 125px)" }}
    >
      <ProConfigProvider hashed={false}>
        <div className="bg-white">
          <LoginForm
            logo="https://xinggui-1311139524.cos.ap-guangzhou.myqcloud.com/logo.png"
            title="用户登录"
            subTitle="欢迎来到星轨-图书借阅系统"
            onFinish={handleLogin} // 处理登录逻辑
          >
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: "large",
                  prefix: <UserOutlined className={"prefixIcon"} />,
                }}
                placeholder={"请输入您的用户名"}
                rules={[
                  {
                    required: true,
                    message: "请输入用户名!",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined className={"prefixIcon"} />,
                }}
                placeholder={"请输入您的密码"}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                ]}
              />
            </>
            <div
              style={{
                marginBlockEnd: 24,
              }}
              className={"flex justify-between items-center"}
            >
              <NavLink to={"/register"}>去注册</NavLink>
              <a>忘记密码</a>
            </div>
          </LoginForm>
        </div>
      </ProConfigProvider>
    </div>
  );
}
